/**
 * 直接攻击动作
 */
 class Attack extends Action {
	constructor(enity, callback) {
		super();

        this.callback = callback;
		this.enity = enity;
		this.enity.body.velocity.x *= 0.3;
		this.enity.body.velocity.y *= 0.3;
		Matter.Body.setVelocity(this.enity.body, this.enity.body.velocity);

		this.enity.state = "attack";
	}
	
	update() {
		if(this.enity.frame != 2)
			return;

		const sprite = this.enity;
		// 计算计算攻击范围和间隔
		const scene = sprite.scene;
		for(var i = 0; i < scene.children.length; i++) {
			const child = scene.children[i];
			// 如果不是角色则跳过
			if(!child.isCylinder || child.constructor.name!="Character" || (child.action && child.action.constructor.name=="Hurt"))
				continue;

			// 如果child不是攻击者
			if(child != sprite) {
				// 检查与目标点距离
				const xDiff = child.x - sprite.x;
				const yDiff = child.y - sprite.y;
				const distance = Math.sqrt(xDiff*xDiff+yDiff*yDiff);
				
				// 如果在攻击扇形内
				if(distance < sprite.scene.gridSize * 2) {		
					// 攻击成功
					Matter.Body.setVelocity(child.body, {x:xDiff*0.2,y:yDiff*0.2});

					// 受伤动画
					child.hurt();
				}
			}
		}

        this.callback(this);
        this.enity.state = "idea";
	}
}